<?php

class NewsController extends Controller
{
	/**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   public function actionIndex()
	{
		
      $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'news_date_create'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;  
      $list = array();
      $model = new News();
      $model->unsetAttributes();
      $start_date = '';
      $end_date = '';
      $criteria = new CDbCriteria;
      $criteria->limit = $limit;
      $criteria->offset = $start;
      $criteria->order = $sidx . ' ' . $sord;
      if(isset($_POST['News'])){ // Nếu người dùng search
         $model->attributes = $_POST['News'];
         $params = array();         
         if(isset($_POST['start_date']) && $_POST['start_date'] != ''){
            $criteria->addCondition("news_date_create >= :start_date", "AND");
            $start_date = $_POST['start_date'];
            $params[':start_date'] = strtotime(str_replace('/','-',$_POST['start_date']));
         }
         if(isset($_POST['end_date']) && $_POST['end_date'] != ''){
            $criteria->addCondition("news_date_create <= :end_date", "AND");
            $end_date = $_POST['end_date'];
            $params[':end_date'] = strtotime(str_replace('/','-',$_POST['end_date'])) + 86400; //Cuối ngày
         }
         if($model->news_title != ''){
            $criteria->addCondition("news_title like :news_title", "AND");
            $params[':news_title'] = '%'.$model->news_title.'%';
         }
         if($model->news_type >= 0){
            $criteria->addCondition("news_type =:news_type");
            $params[':news_type'] = $model->news_type;
         }
         $criteria->params = $params;
         //CVarDumper::dump($criteria->params,10,true);die();
         $object = $model->findAll($criteria);
      }else{
         $object = $model->findAll($criteria);   
      }
      //CVarDumper::dump($object,10,true);die();
      if(count($object) > 0){
         foreach($object as $item){
            $list[$item->attributes['news_id']] = $item->attributes;
         }
      }
      //CVarDumper::dump($list,10,true);die();
      $total_record = $model->count($criteria); // Đếm tổng số bản ghi
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
      $types = array(
         -1 => '-- Chọn 1 loại tin --',
         'Tin tức',
         'Dịch vụ',
         'Khuyến mại',
      );
      
      $this->render('index',array(
         "model" => $model,
         "session_user" => $session_user,
         "start_date" => $start_date,
         "end_date" => $end_date,
         "types" => $types,
         "list" => $list,
         "rowList" => $rowList,
         "page" => $page,
         "start" => $start,
         "limit" => $limit,
         "total_record" => $total_record,
         "total_pages" => $total_pages,
      ));
	}
   
   /**
    * 
    * Display page create
   */
   public function actionCreate(){
      $model = new News();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['News'])){
         $model->attributes = $_POST['News'];
         $model->news_date_create = time();
         if($model->validate()){
            if($model->save()){
               $message = "Đăng tin thành công";   
               
               //Upload image
               $images = CUploadedFile::getInstancesByName('News');
               if(isset($images) && count($images)> 0)
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/news/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){    
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $news = News::Model()->findByPk($model->news_id);
                           $news->news_image = $fileName;
                           $news->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(140);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);               
                     }                
                  }
               }
            }
            
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      $this->pageTitle = 'Đăng tin tức';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array(
         'model'=>$model,                                    
         'session_user' => $session_user,
         'message' => $message,
      ));
   }
   
   /**
    * 
    * Display page edit
   */
   public function actionEdit($id){
      $model = News::model()->findByPk($id);
      $old_image = $model->news_image;
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['News'])){
         $model->attributes = $_POST['News'];
         //Upload image
         $images = CUploadedFile::getInstancesByName('News');
         if(count($images) == 0){
            $model->news_image = $old_image;
         }
         if($model->validate()){
            if($model->save()){
               $message = "Cập nhật tin tức thành công";   
               if(isset($images) && count($images)> 0){
                  $i = 0;
                  foreach ($images as $image=>$pic){
                     $i++;
                     //Rename file image
                     $fileName = date('YmdHis',time()).$i;
                     switch($pic->type){
                        case 'image/jpeg':
                           $fileName .= '.jpg';
                           break;
                        case 'image/png':
                           $fileName .='.png';
                           break;
                        default:
                           $fileName .='.gif';
                           break;
                     }
                     $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/news/';
                     if ($pic->saveAs($path_to_upload.$fileName,0777)){
                        $image_unset = $path_to_upload.$old_image;
                        unset($image_unset);
                        //Lay anh dau tien lam anh dai dien
                        if($i == 1){
                           $news = News::Model()->findByPk($model->news_id);
                           $news->news_image = $fileName;
                           $news->save();
                        }
                        
                        //Resize image
                        $simpleImage = new SimpleImage();
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(680);
                        $simpleImage->save($path_to_upload.$fileName);
                        $simpleImage->load($path_to_upload.$fileName);
                        $simpleImage->resizeToWidth(140);
                        $simpleImage->save($path_to_upload.'thumb_'.$fileName);               
                     }                
                  }
               }
             $this->redirect('/admin/'.$this->id);     
            }
         }
            
         if($action_user == 'save'){
            $this->redirect('/index.php/admin/'.$this->id);
         }
         }
      $this->pageTitle = 'Cập nhật tin tức';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array(
         'model'=>$model,                                    
         'session_user' => $session_user,
         'message' => $message,
      ));
   }
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE news SET news_active = 0 WHERE news_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}

   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE news SET news_active = 1 WHERE news_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM news WHERE news_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * HOME record 
   */
   public function actionHome(){
      $id = Yii::app()->request->getParam('id');
      $status = Yii::app()->request->getParam('status');
      $model = News::model()->findByPk($id);
      $model->news_date_modify = time();
      $model->news_is_home = $status;
      $message = '';
      $error = 1;
      if($model->validate()){
         if($model->save()){
            $error = 0;
         }else{
            $error = 1;
         }   
      }
      $message = $model->errors;
      echo json_encode(array('error' => $error,'message' => $message));
   }
   
   /**
    * SLIDE record 
   */
   public function actionSlide(){
      $id = Yii::app()->request->getParam('id');
      $status = Yii::app()->request->getParam('status');
      $model = News::model()->findByPk($id);
      $model->news_date_modify = time();
      $model->news_is_slide = $status;
      $message = '';
      $error = 1;
      if($model->validate()){
         if($model->save()){
            $error = 0;
         }else{
            $error = 1;
         }   
      }
      $message = $model->errors;
      echo json_encode(array('error' => $error,'message' => $message));
   }
   

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}